package com.proxyhub.controller;

import com.proxyhub.crawler.CrawlerStarter;
import com.proxyhub.repo.ProxyRepo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by linxsh on 2017/6/15.
 */
@Controller
public class ProxyController {

    @Autowired
    private CrawlerStarter starter;

    @Autowired
    private ProxyRepo proxyRepo;

    /**
     * 更新代理池中的数据
     * @return
     */
    @ResponseBody
    @GetMapping("/update")
    public String update(HttpServletRequest request) {
        starter.start(request);
        return "update success";
    }

    @ResponseBody
    @GetMapping(value = {"/fetch", "/fetch/{num}"})
    public Object fetch(@PathVariable("num")String num) {
        if(StringUtils.isNotBlank(num)) {
            return proxyRepo.findAll();
        }
        return proxyRepo.fetch(NumberUtils.toInt(num, 10));
    }
}
